package com.xbfinal.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xbfinal.reggie.common.R;
import com.xbfinal.reggie.pojo.Category;
import com.xbfinal.reggie.pojo.Employee;
import com.xbfinal.reggie.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;


    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        final boolean save = categoryService.save(category);
        if(save){
            return R.success("新增成功");
        }else {
            return R.error("新增失败");
        }

    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        final Page<Category> categoryPage = new Page<>(page,pageSize);
        //        条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper();
        //        添加排序条件
        lambdaQueryWrapper.orderByAsc(Category::getSort);
        // 进行分页查询
        categoryService.page(categoryPage,lambdaQueryWrapper);
        return R.success(categoryPage);
    }


    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){

        final boolean b = categoryService.removeById(ids);
        if(b){
            return  R.success("删除成功");
        }else {
            return  R.error("删除失败");
        }

    }


    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        //由于前面家里自定义得元处理器，就不用我们自己加 创建人 创建时间了
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */

    @GetMapping("/list")
    public R<List<Category>> listR(Category category){
        //条件构造器
        final LambdaQueryWrapper<Category> lambdaQueryWrapper
                = new LambdaQueryWrapper();
        //添加条件
        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());

        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        //放入List集合
        List<Category> list=categoryService.list(lambdaQueryWrapper);
    return R.success(list);
    }
}
